package com.shenyue.nbtownlet.fragment;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chanven.lib.cptr.PtrDefaultHandler;
import com.chanven.lib.cptr.PtrFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.OrganizationPersonnelListViewAdapter;
import com.shenyue.nbtownlet.base.BaseFragment;
import com.shenyue.nbtownlet.databinding.OrganizationPersonnelFragmentBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppContactsModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.util.ActivityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.NetWorkUtils;
import com.shenyue.nbtownlet.util.StringUtil;

/**
 * 机构人员
 */

public class OrganizationPersonnelFragment extends BaseFragment implements OrganizationPersonnelListViewAdapter.OrganizationPersonnelItemClickListener, View.OnClickListener {
    private OrganizationPersonnelFragmentBinding binding;
    private OrganizationPersonnelListViewAdapter listViewAdapter;
    private int pageNo = 1, pageSize = 10;
    private Handler mHandler = new Handler();
    private Context mContext;
    private boolean isLoading = false;
    private JSONObject $data = new JSONObject();

    public static BaseFragment newInstance(String name) {
        Bundle args = new Bundle();
        args.putString("name", name);
        BaseFragment fragment = new OrganizationPersonnelFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.organization_personnel_fragment, container, false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        mContext = getActivity();

        listViewAdapter = new OrganizationPersonnelListViewAdapter(mContext);
        binding.listView.setAdapter(listViewAdapter);
        listViewAdapter.setOnItemClickListener(this);

        binding.ptrClassicFrameLayout.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(getString(R.string.no_network));
                    return;
                }
                query();
            }
        });

        binding.ptrClassicFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                if (!NetWorkUtils.isNetworkConnected(mContext)) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(getString(R.string.no_network));
                    return;
                }
                queryMore();
            }
        });
        binding.ptrClassicFrameLayout.disableWhenHorizontalMove(true);

        binding.dInfo.setOnClickListener(this);
        binding.btnMobile.setOnClickListener(this);
        binding.btnPhone.setOnClickListener(this);
        binding.btnSms.setOnClickListener(this);
        binding.btnCollect.setOnClickListener(this);
        binding.btnCollectU.setOnClickListener(this);
    }

    @Override
    public void setLoading(boolean loading) {
        isLoading = loading;
    }

    private void query() {
        listViewAdapter.clear();
        pageNo = 1;
        if ($data.isEmpty() || $data.getBooleanValue("all")) {//全部
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("areaid", StringUtil.isNull(AppModel.getStreetId(mContext)) ? AppModel.getAreaId(mContext) : AppModel.getStreetId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            param.put("isall", $data.getBooleanValue("all"));
            AppContactsModel.GetUserInfo(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.setLoadMoreEnable(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(error);
                }
            });
        } else if ($data.getBooleanValue("people")) {//人员搜索
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("name", $data.getString("name"));
            param.put("areaid", StringUtil.isNull(AppModel.getStreetId(mContext)) ? AppModel.getAreaId(mContext) : AppModel.getStreetId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            AppContactsModel.GetUserInfoListByName(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.setLoadMoreEnable(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(error);
                }
            });
        } else if ($data.getBooleanValue("collect")) {
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("userId", AppLoginModel.getIdentityId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            AppContactsModel.GetCollectList(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.setLoadMoreEnable(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.refreshComplete();
                    showMsg(error);
                }
            });
        }
    }

    private void queryMore() {
        pageNo += 1;
        if ($data.isEmpty() || $data.getBooleanValue("all")) {//全部
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("areaid", StringUtil.isNull(AppModel.getStreetId(mContext)) ? AppModel.getAreaId(mContext) : AppModel.getStreetId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            param.put("isall", $data.getBooleanValue("all"));
            AppContactsModel.GetUserInfo(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.loadMoreComplete(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(error);
                }
            });
        } else if ($data.getBooleanValue("people")) {//人员搜索
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("name", $data.getString("name"));
            param.put("areaid", StringUtil.isNull(AppModel.getStreetId(mContext)) ? AppModel.getAreaId(mContext) : AppModel.getStreetId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            AppContactsModel.GetUserInfoListByName(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.loadMoreComplete(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(error);
                }
            });
        } else if ($data.getBooleanValue("collect")) {
            JSONObject param = new JSONObject();
            param.put("type", "2");
            param.put("userId", AppLoginModel.getIdentityId(mContext));
            param.put("pageIndex", pageNo);
            param.put("pageSize", pageSize);
            AppContactsModel.GetCollectList(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONArray array = JSON.parseArray(val);
                    binding.ptrClassicFrameLayout.loadMoreComplete(!(array.size() < pageSize));
                    listViewAdapter.addItems(array);
                }

                @Override
                public void error(String error, String action) {
                    binding.ptrClassicFrameLayout.loadMoreComplete(false);
                    showMsg(error);
                }
            });
        }
    }

    @Override
    public void refresh(JSONObject data) {
        binding.dInfo.setVisibility(View.GONE);
        if (data == null && isLoading)
            return;
        isLoading = true;
        if (data == null) {
            $data = new JSONObject();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    binding.ptrClassicFrameLayout.autoRefresh();
                }
            }, 32);
            return;
        }

        $data = JSON.parseObject(data.toString());
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                binding.ptrClassicFrameLayout.autoRefresh();
            }
        }, 32);
    }

    @Override
    public void willBeDisplayed() {
        binding.dInfo.setVisibility(View.GONE);
    }

    @Override
    public void onItemClick(int position) {
        if (!NetWorkUtils.isNetworkConnected(mContext)) {
            showMsg(getString(R.string.no_network));
            return;
        }
        final JSONObject item = (JSONObject) listViewAdapter.getItem(position);
        String HEADPORTRAIT = item.getString("HEADPORTRAIT");
        GlideUtil.loadImg(mContext, HEADPORTRAIT, binding.HEADPORTRAIT);

        binding.btnCollect.setTag(item.toString());
        binding.btnCollectU.setTag(item.toString());
        binding.REALNAME.setText(item.getString("REALNAME"));
        binding.ORGANNAME.setText(item.getString("ORGANNAME"));
        binding.MOBILE.setText(item.getString("MOBILE"));
        binding.Duty.setText(StringUtil.getValue(item.getString("Duty")));
        String TEL = StringUtil.getValue(item.getString("TEL"));
        if (!TEL.contains("0574-"))
            TEL = "0574-" + TEL;
        binding.TEL.setText(TEL);
        changeCollectView(AppModel.UN_COLLECTED);
        binding.dInfo.setVisibility(View.VISIBLE);

        //获取收藏状态
        JSONObject param = new JSONObject();
        param.put("userId", AppLoginModel.getIdentityId(mContext));
        param.put("beuserid", StringUtil.dTs(item.getString("ID")));
        AppContactsModel.GetCollectStatus(mContext, param, new BaseListener() {
            @Override
            public void success(String val, String action) {
                JSONObject result = JSON.parseObject(val);
                String status = result.getString("result");
                changeCollectView(status);
            }

            @Override
            public void error(String error, String action) {
                showMsg(error);
            }
        });
    }

    private void changeCollectView(String status) {
        if (AppModel.COLLECTED.equals(status)) {
            binding.btnCollectU.setVisibility(View.GONE);
            binding.btnCollect.setVisibility(View.VISIBLE);
        } else if (AppModel.UN_COLLECTED.equals(status)) {
            binding.btnCollectU.setVisibility(View.VISIBLE);
            binding.btnCollect.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.d_info:
                binding.dInfo.setVisibility(View.GONE);
                break;
            case R.id.btn_mobile: {
                ActivityUtil.call(mContext, binding.MOBILE.getText().toString());
                break;
            }
            case R.id.btn_phone: {
                ActivityUtil.call(mContext, binding.TEL.getText().toString());
                break;
            }
            case R.id.btn_sms: {
                ActivityUtil.sms(mContext, binding.MOBILE.getText().toString());
                break;
            }
            case R.id.btn_collect:
                changeCollectServer(AppModel.COLLECTED, JSON.parseObject((String) v.getTag()));
                break;
            case R.id.btn_collect_u:
                changeCollectServer(AppModel.UN_COLLECTED, JSON.parseObject((String) v.getTag()));
                break;
        }
    }

    private void changeCollectServer(String status, JSONObject item) {
        if (AppModel.COLLECTED.equals(status)) {
            JSONObject param = new JSONObject();
            param.put("userId", AppLoginModel.getIdentityId(mContext));
            param.put("beuserid", StringUtil.dTs(item.getString("ID")));
            AppContactsModel.GetIsDeleteCollectSuccess(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONObject result = JSON.parseObject(val);
                    String status = result.getString("result");
                    if ("1".equals(status)) {
                        showMsgS("取消收藏成功");
                        changeCollectView(AppModel.UN_COLLECTED);
                    } else
                        showMsg("取消收藏失败");
                }

                @Override
                public void error(String error, String action) {
                    showMsg(error);
                }
            });
        } else if (AppModel.UN_COLLECTED.equals(status)) {
            JSONObject param = new JSONObject();
            param.put("userId", AppLoginModel.getIdentityId(mContext));
            param.put("beuserid", StringUtil.dTs(item.getString("ID")));
            AppContactsModel.GetIsCollectSuccess(mContext, param, new BaseListener() {
                @Override
                public void success(String val, String action) {
                    JSONObject result = JSON.parseObject(val);
                    String status = result.getString("result");
                    if ("1".equals(status)) {
                        showMsgS("收藏成功");
                        changeCollectView(AppModel.COLLECTED);
                    } else
                        showMsg("收藏失败");
                }

                @Override
                public void error(String error, String action) {
                    showMsg(error);
                }
            });
        }
    }
}
